<template>
  <div class="pays">
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="box-container">
        <div class="box-title">费用信息</div>
        <div class="box-th-container">
          <span class="box-th-item"
            >公司名称：{{ ruleForm.invoiceHeadName }}</span
          >
          <span class="box-th-item"
            >应缴金额(元)：{{ tableData.totalAmount }}</span
          >
        </div>
      </div>

      <div v-if="tableData.mrCostWaters">
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">水费</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.waterTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show1" @click="show1 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show1 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.mrCostWaters"
          :table-loading="tableLoading"
          :option="tableOptionPayment1"
          v-if="show1"
        >
        </avue-crud>
      </div>
      <div v-if="tableData.mrCostElectrics">
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">电费</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.electricTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show7" @click="show7 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show7 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.mrCostElectrics"
          :table-loading="tableLoading"
          :option="tableOptionPayment1"
          v-if="show7"
        >
        </avue-crud>
      </div>
      <div v-if="tableData.carCosts && tableData.carCosts.length > 0">
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">停车费</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.carCostTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show2" @click="show2 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show2 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.carCosts"
          :table-loading="tableLoading"
          :option="tableOptionPayment4"
          v-if="show2"
        >
        </avue-crud>
      </div>
      <div v-if="tableData.ctCostLeases && tableData.ctCostLeases.length > 0">
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">租赁费</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.leaseTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show3" @click="show3 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show3 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.ctCostLeases"
          :table-loading="tableLoading"
          :option="tableOptionPayment2"
          v-if="show3"
        >
        </avue-crud>
      </div>
      <div
        v-if="
          tableData.ctCostmanagements && tableData.ctCostmanagements.length > 0
        "
      >
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">市场管理服务费</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.managementTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show4" @click="show4 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show4 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.ctCostmanagements.length > 0"
          :table-loading="tableLoading"
          :option="tableOptionPayment2"
        >
        </avue-crud>
      </div>
      <div
        v-if="
          tableData.ctCostGuarantees && tableData.ctCostGuarantees.length > 0
        "
      >
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">保证金</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.guaranteeTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show5" @click="show5 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show5 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.ctCostGuarantees.length > 0"
          :table-loading="tableLoading"
          :option="tableOptionPayment2"
          v-if="show5"
        >
        </avue-crud>
      </div>
      <div v-if="tableData.cOtherCost && tableData.cOtherCost.length > 0">
        <p class="payment-title">
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">其他费用</el-col>
            <el-col :span="6"
              >合计金额：{{ tableData.cOtherCostTotalAmount }}元</el-col
            >
            <el-col :span="6" style="text-align: right">
              <i class="el-icon-arrow-down" v-if="show6" @click="show6 = 0"></i>
              <i class="el-icon-arrow-up" v-else @click="show6 = 1"></i>
            </el-col>
          </el-row>
        </p>
        <avue-crud
          ref="crud"
          menu="false"
          :data="tableData.cOtherCost"
          :table-loading="tableLoading"
          :option="tableOptionPayment3"
          v-if="show6"
        >
        </avue-crud>
      </div>
      <div class="box-container">
        <div class="box-title">支付信息</div>
        <div class="box-th-container" style="padding: 20px 0px">
          <el-form
            :inline="true"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="200px"
          >
            <el-form-item label="支付方式" prop="payType">
              <el-select
                v-model="ruleForm.payType"
                placeholder="请选择支付方式"
              >
                <el-option
                  v-for="(item, index) in options"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="实收金额" prop="totalAmount">
              <el-input
                v-model="ruleForm.totalAmount"
                placeholder="实收金额"
              ></el-input>
            </el-form-item>
            <el-form-item label="是否开票">
              <el-radio-group
                v-model="ruleForm.isInvoice"
                @change="resourceChange"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="发票类型"
              prop="invoiceType"
              v-if="ruleForm.isInvoice == 1"
            >
              <el-select
                @change="invoiceTypeChange"
                v-model="ruleForm.invoiceType"
                placeholder="请选择发票类型"
              >
                <el-option
                  v-for="(item, index) in invoiceoptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="发票抬头"
              prop="invoiceHead"
              v-if="ruleForm.isInvoice == 1"
            >
              <el-radio-group
                v-model="ruleForm.invoiceHead"
                @change="radioChange"
              >
                <el-radio-button label="0">单位</el-radio-button>
                <el-radio-button label="1" :disabled="ruleForm.invoiceType == 2"
                  >个人</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="单位名称"
              prop="invoiceHeadName"
              v-if="ruleForm.isInvoice == 1"
            >
              <el-input
                v-model="ruleForm.invoiceHeadName"
                placeholder="单位名称"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="纳税人识别号"
              v-if="ruleForm.isInvoice == 1 && ruleForm.invoiceHead != 1"
              prop="number"
            >
              <el-input
                v-model="ruleForm.number"
                placeholder="请填写纳税人识别号"
              ></el-input>
            </el-form-item>

            <el-col :span="24" v-if="ruleForm.isInvoice == 1">
              <el-form-item
                v-for="(item, index) in imInvoiceCostTypeVos1"
                label="发票票号"
                :key="item.key"
                :rules="{
                  required: true,
                  message: '请填写发票编号',
                  trigger: 'blur',
                }"
              >
                <el-input
                  v-model="item.invoiceNumber"
                  style="width: 200px; float: left; margin-right: 10px"
                ></el-input>
                <el-select
                  multiple
                  v-model="item.costType"
                  placeholder="请选择对应费用类型"
                  style="width: 200px; float: left; margin-right: 10px"
                >
                  <el-option
                    v-for="(items, index) in costTypeOptions"
                    :key="index"
                    :label="items.label"
                    :value="items.value"
                  ></el-option>
                </el-select>
                <el-button
                  @click.prevent="removeInvoiceNumber(item, 1)"
                  style="float: left"
                  v-if="index > 0"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  @click="addInvoiceNumber(1)"
                  icon="el-icon-plus"
                  v-if="index == 0"
                  >新增发票号</el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="ruleForm.isInvoice == 1">
              <el-form-item
                v-for="(item, index) in imInvoiceCostTypeVos2"
                label="收据票号"
                :key="item.key"
                :rules="{
                  required: true,
                  message: '请填写发票编号',
                  trigger: 'blur',
                }"
              >
                <el-input
                  v-model="item.invoiceNumber"
                  style="width: 200px; float: left; margin-right: 10px"
                ></el-input>
                <el-select
                  v-model="item.costType"
                  placeholder="请选择对应费用类型"
                  style="width: 200px; float: left; margin-right: 10px"
                >
                  <el-option
                    v-for="(items, index) in costTypeOptions"
                    :key="index"
                    :label="items.label"
                    :value="items.value"
                  ></el-option>
                </el-select>
                <el-button
                  @click.prevent="removeInvoiceNumber(item, 2)"
                  style="float: left"
                  v-if="index > 0"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  @click="addInvoiceNumber(2)"
                  icon="el-icon-plus"
                  v-if="index == 0"
                  >新增收据票号</el-button
                >
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" icon="el-icon-circle-close"
          >取 消</el-button
        >
        <el-button
          icon="el-icon-circle-check"
          type="primary"
          @click="submitForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  tableOptionPayment1,
  tableOptionPayment2,
  tableOptionPayment3,
  tableOptionPayment4,
} from "@/const/crud/cost/detail";
import {
  fetchPayDetails,
  addInvoice,
  confirmPayments,
} from "@/api/cost/paymentscost";
import { getDicType } from "@/api/common";
import { syscompanyid } from "@/api/market/contract/person";
export default {
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      title: '',
      tableOptionPayment1,
      tableOptionPayment2,
      tableOptionPayment3,
      tableOptionPayment4,
      dialogVisible: false,
      costTypeOptions: [],
      tableData: [],
      action: "",
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      that: this,
      info: null,
      options: [],
      invoiceoptions: [
        {
          label: "增值税普通发票",
          value: 1,
        },
        {
          label: "增值税专用发票",
          value: 2,
        },
      ],
      isRequest: true,
      isInvoice: 1,
      companyId: 0,
      ruleForm: {
        totalAmount: 0,
        payType: "",
        isInvoice: 1,
        invoiceType: 1,
        invoiceHead: 0,
        invoiceHeadName: "",
        number: "",
        companyId: "",
        imInvoiceCostTypeVos: [],
      },
      rules: {
        payType: [
          { required: true, message: "请选择支付方式", trigger: "change" },
        ],
        totalAmount: [
          { required: true, message: "请填写实收金额", trigger: "change" },
        ],
        invoiceType: [
          { required: true, message: "请选择发票类型", trigger: "change" },
        ],
        invoiceHead: [
          { required: true, message: "请选择发票抬头", trigger: "change" },
        ],
      },
      imInvoiceCostTypeVos1: [{ invoiceNumber: "", costType: "", type: 1 }],
      imInvoiceCostTypeVos2: [{ invoiceNumber: "", costType: "", type: 3 }],
      show1: 1,
      show2: 1,
      show3: 1,
      show4: 1,
      show5: 1,
      show6: 1,
      show7: 1,
    };
  },
  filters: {
    getCostType(value, that) {
      let str = "";
      that.costTypeOptions.forEach((item) => {
        if (value == item.value) {
          str = item.label;
        }
      });
      return str;
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    resourceChange() {
      this.ruleForm.invoiceType = 1;
      this.ruleForm.invoiceHead = 0;
      this.ruleForm.invoiceHeadName = "";
    },
    invoiceTypeChange() {
      if (this.ruleForm.invoiceType == 1) {
        //普通发票
        this.ruleForm.invoiceHead = 1;
      }
    },
    radioChange() {
      // this.ruleForm.invoiceHeadName = ''
      if (this.ruleForm.invoiceHead == 0) {
        //this.ruleForm.invoiceHeadName = this.item.invoiceHeadName
      }
    },
    refreshChange() {
      this.getList();
    },
    refreshList() {
      this.refreshChange();
    },
    selectionChange(list) {
      // this.$message.success('选中的数据' + JSON.stringify(list));
      this.selectList = [];
      this.selectList = list;
    },
    exportExcel(id) {
      ExportFile("/cost/mrcost/export", { id: id });
    },
    detail(id) {
      this.$refs.detail.init(id);
    },
    handleClose() {
      this.dialogVisible = false;
    },
    init(row) {
      this.title = this.action == 'payment' ? "缴费" :"开票";
      this.tableData = [];
      getDicType("cost_type").then((res) => {
        this.costTypeOptions = res.data.data;
      });
      getDicType("payment_method").then((res) => {
        this.options = res.data.data;
      });
      this.dialogVisible = true;
      this.isRequest = true;
      this.companyId = parseInt(row[0].companyId);
      this.ruleForm.companyId = this.companyId;

      this.imInvoiceCostTypeVos1 = [{ invoiceNumber: "", costType: "", type: 1 }];
      this.imInvoiceCostTypeVos2 = [{ invoiceNumber: "", costType: "", type: 3 }];

      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields();
      }
      this.getList(row);
      syscompanyid({}, parseInt(this.companyId)).then((res) => {
        if(res.data.data){
          this.ruleForm.number = res.data.data.companyCode;
        }
        this.ruleForm.invoiceHeadName = res.data.data.companyName;
      });
    },

    getList(row) {
      let params = {
        companyId: parseInt(row[0].companyId),
      };
      let waterIds = [],
        leaseIds = [],
        managementIds = [],
        electricIds = [],
        cOtherCostIds = [],
        carCostIds = [],
        guaranteeIds = [];

      row.forEach((item, index) => {
        switch (item.costType) {
          case "3":
            waterIds.push(item.id);
            params.waterIds = waterIds.join(",");
            this.ruleForm.waterIds = waterIds.join(",");
            break; //水费
          case "4":
            electricIds.push(item.id);
            params.electricIds = electricIds.join(",");
            this.ruleForm.electricIds = electricIds.join(",");
            break; //电费
          case "5":
            cOtherCostIds.push(item.id);
            params.cOtherCostIds = cOtherCostIds.join(",");
            this.ruleForm.cOtherCostIds = cOtherCostIds.join(",");
            break; //其他费用
          case "6":
            carCostIds.push(item.id);
            params.carCostIds = carCostIds.join(",");
            this.ruleForm.carCostIds = carCostIds.join(",");
            break; //停车费
          case "7":
          case "8":
          case "9":
            guaranteeIds.push(item.id);
            params.guaranteeIds = guaranteeIds.join(",");
            this.ruleForm.guaranteeIds = guaranteeIds.join(",");
            break; //活动场地租赁保证金
          case "1":
            leaseIds.push(item.id);
            params.leaseIds = leaseIds.join(",");
            this.ruleForm.leaseIds = leaseIds.join(",");
            break; //租金
          case "2":
            managementIds.push(item.id);
            params.managementIds = managementIds.join(",");
            this.ruleForm.managementIds = managementIds.join(",");
            break; //市场管理服务费
        }
      });

      fetchPayDetails(params)
        .then((response) => {
          this.ruleForm.totalAmount = response.data.data.totalAmount;
          this.tableData = response.data.data;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList();
    },
    addInvoiceNumber(type) {
      if (type == 1) {
        this.imInvoiceCostTypeVos1.push({
          invoiceNumber: "",
          costType: "",
          type: 1,
        });
      } else {
        this.imInvoiceCostTypeVos2.push({
          invoiceNumber: "",
          costType: "",
          type: 1,
        });
      }
    },
    removeInvoiceNumber(item, type) {
      if (type == 1) {
        var index = this.imInvoiceCostTypeVos1.indexOf(item);
        if (index !== -1) {
          this.imInvoiceCostTypeVos1.splice(index, 1);
        }
      } else {
        var index = this.imInvoiceCostTypeVos2.indexOf(item);
        if (index !== -1) {
          this.imInvoiceCostTypeVos2.splice(index, 1);
        }
      }
    },
    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        let ins = [];
        if (this.imInvoiceCostTypeVos1) {
          for (let index in this.imInvoiceCostTypeVos1) {
            let intemp = this.imInvoiceCostTypeVos1[index];
            if (intemp.invoiceNumber) {
              intemp.costType = intemp.costType.join(',');
              ins.push(intemp);
            }
          }
        }
        if (this.imInvoiceCostTypeVos2) {
          for (let index in this.imInvoiceCostTypeVos2) {
            let intemp = this.imInvoiceCostTypeVos2[index];
            if (intemp.invoiceNumber) {
              intemp.costType = intemp.costType.join(',');
              ins.push(intemp);
            }
          }
        }
        if (ins.length == 0) {
          return false;
        }
        this.ruleForm.imInvoiceCostTypeVos = ins;
        if (valid) {
          if (!this.isRequest) {
            return;
          }
          this.isRequest = false;
          if (this.tableData.waterTotalAmount) {
            this.ruleForm.waterTotalAmount = this.tableData.waterTotalAmount;
          }
          if (this.tableData.leaseTotalAmount) {
            this.ruleForm.leaseTotalAmount = this.tableData.leaseTotalAmount;
          }
          if (this.tableData.managementTotalAmount) {
            this.ruleForm.managementTotalAmount = this.tableData.managementTotalAmount;
          }
          if (this.tableData.electricTotalAmount) {
            this.ruleForm.electricTotalAmount = this.tableData.electricTotalAmount;
          }
          if (this.tableData.cOtherCostTotalAmount) {
            this.ruleForm.cOtherCostTotalAmount = this.tableData.cOtherCostTotalAmount;
          }
          if (this.tableData.carCostTotalAmount) {
            this.ruleForm.carCostTotalAmount = this.tableData.carCostTotalAmount;
          }
          if (this.tableData.guaranteeTotalAmount) {
            this.ruleForm.guaranteeTotalAmount = this.tableData.guaranteeTotalAmount;
          }
          console.log(this.ruleForm);
          if (this.action == "invoice") {
            addInvoice(this.ruleForm)
              .then((data) => {
                this.$message.success("开票成功");
                this.dialogVisible = false;
                this.isRequest = true;
                this.$emit("refreshList");
              })
              .catch(() => {
                loading();
              });
          } else {
            confirmPayments(this.ruleForm)
              .then((data) => {
                this.$message.success("缴费成功");
                this.dialogVisible = false;
                this.isRequest = true;
                this.$emit("refreshList");
              })
              .catch(() => {
                loading();
              });
          }
        }
      });
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss'>
//@import url(); 引入公共css类
.pays .avue-crud__menu {
  display: none !important;
}
.box-title {
  height: 50px;
  line-height: 50px;
  background-color: rgba(215, 215, 215, 1);
  color: #7f7f7f;
  font-size: 16px;
  padding: 0 20px;
  font-weight: bold;

  &.bold {
    background-color: rgba(127, 127, 127, 1);
    color: #fff;
  }
}

.box-th-container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
  font-size: 14px;
  color: #aaa;
  .box-th-item {
    width: 25%;
    margin: 15px 0 10px;
    &.red {
      color: #f00;
    }
  }
}
.payment-title {
  height: 50px;
  line-height: 50px;
  background-color: #d7d7d7;
  color: #7f7f7f;
  font-size: 16px;
  padding: 0 20px;
  font-weight: bold;
}
</style>
